﻿
using NB.MGJ.Common;
using NB.MGJ.Common.MVC;
using NB.MGJ.Model;
using NB.MGJ.Service;
using NB.MGJ.Service.CodeManage;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;


namespace NB.MGJ.Web.Controllers
{
    public class DBHController : BaseController
    {
        private GenCodeBatchService _CodeBatchService = new GenCodeBatchService();
        private CommonService _com = new CommonService();
        private CodeManageService _codeManageService = new CodeManageService();
        private ManagerService _manager = new ManagerService();
        public DBHService dbh = new DBHService();

        public DBHController()
        {

        }


        public ActionResult GetPCR(int PID, int CID, int RID)
        {
            AddressBoxModel pcr = new AddressBoxModel();
            pcr.PList = _com.GetPCRModel(PID);
            pcr.CList = _com.GetPCRModel(CID);
            pcr.RList = _com.GetPCRModel(RID);
            return Json(pcr);
        }


        /// <summary>
        /// 上传 图片 || 记事本 
        /// </summary>
        /// <param name="file">图片对象</param>
        /// <param name="savePath">保存路径</param>
        /// <param name="fName">保存的文件名称</param>
        /// <returns></returns>
        public string UploadImg(HttpPostedFileBase file, string savePath, string fName)
        {
            try
            {

                string _path = Path.Combine(savePath, fName);
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }
                string furl = savePath + fName;
                file.SaveAs(furl);
                return _path;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="file"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public JsonResult UploadImgPath(HttpPostedFileBase file, string path, string fname)
        {
            try
            {
                bool _result = false;
                string _message = string.Empty;
                string _path = string.Empty;
                string webPath = string.Empty;
                List<string> _extensionlist = new List<string>() { ".jpg", ".jpeg", ".bmp", ".png" };
                if (file == null || file.ContentLength == 0)
                    _message = "上传失败";
                else if (file.ContentLength > (1 * 1024 * 1024))
                    _message = "图片不大于1M";
                else
                {
                    string ex = Path.GetExtension(file.FileName);
                    if (!_extensionlist.Contains(ex))
                        _message = "不支持的图片类型";
                    else
                    {
                        string name = fname + ex;
                        EncryptHelper _eh = new EncryptHelper();
                        if (!Directory.Exists(Server.MapPath(path)))
                        {
                            Directory.CreateDirectory(Server.MapPath(path));
                        }
                        _path = Server.MapPath(path) + "/" + name;
                        webPath = path + "/" + name;
                        file.SaveAs(_path);

                        _result = true;
                    }
                }
                return Json(new { state = _result, message = _message, fileName = webPath });
            }
            catch (Exception ex)
            {

                throw ex;
            }
            //return Json("1");
        }

        /// <summary>
        /// 删除指定路径文件
        /// </summary> 
        /// <param name="path"></param>
        public void DelFile(string path)
        {
            try
            {
                FileInfo file = new FileInfo(Server.MapPath(path));
                if (file.Exists)
                {
                    file.Delete();
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }

        }


        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="file"></param>
        /// <returns>成功 返回：图片路径，失败返回字符串：上传失败</returns>
        public string UploadImg2(HttpPostedFileBase file)
        {
            bool _result = false;
            string _message = string.Empty;
            string _avatarname = string.Empty;

            List<string> _extensionlist = new List<string>() { ".jpg", ".jpeg", ".bmp", ".png" };
            if (file == null || file.ContentLength == 0)
                _message = "上传失败";
            else if (file.ContentLength > (1 * 1024 * 1024))
                _message = "图片不大于1M";
            else
            {
                string ex = Path.GetExtension(file.FileName).ToLower();
                if (!_extensionlist.Contains(ex))
                    _message = "不支持的图片类型";
                else
                {
                    EncryptHelper _eh = new EncryptHelper();
                    _avatarname = _eh.Md5(DateTime.Now.Ticks.ToString()) + ex;
                    string _path = Path.Combine(Server.MapPath("/Content/userImgs/EnterpriseImg"), _avatarname);
                    file.SaveAs(_path);
                    _result = true;
                }
            }

            if (_result)
            {
                return "/Content/userImgs/EnterpriseImg/" + _avatarname;
            }
            return "上传失败";

        }
        /// <summary>
        /// 分片上传文件
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest()
        {
            string folder = Constant._filePath + DateTime.Today.ToString("yyyyMMdd");

            if (!Directory.Exists(folder))//判断文件夹是否存在
            {
                Directory.CreateDirectory(folder);
            }
            // context.Response.ContentType = "text/plain";
            //如果进行了分片
            if (HttpContext.Request.Form.AllKeys.Any(m => m == "chunk"))
            {
                //取得chunk和chunks
                int chunk = Convert.ToInt32(HttpContext.Request.Form["chunk"]);//当前分片在上传分片中的顺序（从0开始）
                int chunks = Convert.ToInt32(HttpContext.Request.Form["chunks"]);//总分片数

                var file = HttpContext.Request.Files[0];
                //根据GUID创建用该GUID命名的临时文件夹
                //  string filePath=@"E:/UpLoadFiles/"+DateTime.Today.ToString("yyyyMMdd")+"/"+file.FileName;

                string filePath = folder + "/" + file.FileName;

                file.SaveAs(filePath);
                using (FileStream fs = new FileStream(filePath, FileMode.Append))
                {
                    byte[] rs = new byte[file.ContentLength];
                    file.InputStream.Read(rs, 0, file.ContentLength);
                    fs.Write(rs, 0, rs.Length);
                    fs.Close();
                }


                HttpContext.Response.Write(filePath);
            }
            else//没有分片直接保存
            {
                var file = HttpContext.Request.Files[0];
                string filePath = folder + "/" + file.FileName;

                file.SaveAs(filePath);

                HttpContext.Request.Files[0].SaveAs(filePath);
                HttpContext.Response.Write(filePath);
            }
        }
    }
}